package com.wql.service.impl;

import com.aaa.entity.OOrder;
import com.aaa.util.JwtUtil;
import com.aaa.util.PayUtils;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxpay.sdk.WXPayUtil;
import com.wql.mapper.GGoodsMapper;
import com.wql.mapper.OPayLogMapper;
import com.wql.mapper.OStockMapper;
import com.wql.service.OOrderService;
import com.wql.mapper.OOrderMapper;
import com.wql.utils.HttpClient;
import com.wql.utils.WebUtils;
import com.wql.vo.FormData;

import org.apache.commons.lang.text.StrBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
* @author 咕噜咕噜
* @description 针对表【o_order(订单信息)】的数据库操作Service实现
* @createDate 2023-03-04 11:07:28
*/
@Service
public class OOrderServiceImpl extends ServiceImpl<OOrderMapper, OOrder>
    implements OOrderService {

    @Autowired
    private OOrderMapper oOrderMapper;

    @Autowired
    private OPayLogMapper oPayLogMapper;

    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.mch_id}")
    private String mchid;
    @Value("${weixin.api_key}")
    private String apiKey;

    @Override
    public Result   queryAll(Integer currentPage, Integer pageSize, FormData formData) {
        HttpServletRequest request = WebUtils.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> tokenChaim = JwtUtil.getTokenChaim(token);
        Object username = tokenChaim.get("username");
        String telephone = username.toString();
        formData.setTelephone(telephone);
        System.out.println("formData = " + formData);

        PageHelper.startPage(currentPage, pageSize);

        List<OOrder> oOrders = oOrderMapper.queryAll(formData);

        for (OOrder oOrder : oOrders) {
            List<OOrder> oOrders1 = oOrderMapper.selectByCode(oOrder.getCode());
//            int sum = oOrders1.stream().mapToInt(oOrder::getTotalmoney).sum();
            oOrder.setGoodlist(oOrders1);
        }
        PageInfo<OOrder> info = new PageInfo<>(oOrders);

        return new Result(2000, "查询成功", info);
    }

    @Override
    public Result updateSend(String code) {
        oOrderMapper.updateSend(code);
        return new Result(2000, "修改成功");
    }

    @Override
    public Result createCode(PayUtils payUtils) {

            //1.订单号查询订单信息
            QueryWrapper<OOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("code", payUtils.getOrderno());
            wrapper.eq("state", 1);
            List<OOrder> oOrders = oOrderMapper.selectList(wrapper);
        if (oOrders != null) {

                //请求参数的封装
                Map<String, String> params = new HashMap<>();
                params.put("appid", appid);
                params.put("mch_id", mchid);
                params.put("nonce_str", WXPayUtil.generateNonceStr());
                params.put("body", payUtils.getOrderno());
                params.put("out_trade_no", payUtils.getOrderno());
                params.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue() + "");
                params.put("spbill_create_ip", "127.0.0.1");//真实服务器的ip
                params.put("notify_url", "192.168.1.94:8096/geRenCenter");//支付成功后跳转的路径
                params.put("trade_type", "NATIVE");
                try {
                    //2.远程调用微信支付接口
                    HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                    //设置支持https协议的请求
                    httpClient.setHttps(true);
                    //设置xml格式的参数
                    httpClient.setXmlParam(WXPayUtil.generateSignedXml(params, apiKey));
                    //发送请求
                    httpClient.post();

                    //获取返回的结果
                    String content = httpClient.getContent();
                    System.out.println("content = " + content);
                    //把xml转化为map
                    Map<String, String> map = WXPayUtil.xmlToMap(content);
                    if (map.get("result_code").equals("SUCCESS")) {

                        Map<String, Object> map1 = new HashMap<>();
                        map1.put("codeUrl", map.get("code_url"));
                        map1.put("price",payUtils.getTotalmoney());
                        map1.put("title", payUtils.getOrderno());
                        map1.put("orderNo", payUtils.getOrderno());
                        return new Result(2000, "获取二维码地址成功", map1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
                return new Result(5000, "订单失效", null);
        }


    @Override
    public Result queryPayStatus(String orderno) {
        Map<String, String> codemap = new HashMap<>();
        codemap.put("appid",appid);
        codemap.put("mch_id",mchid);
        codemap.put("out_trade_no",orderno);
        codemap.put("nonce_str",WXPayUtil.generateNonceStr());
        try {
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setHttps(true);
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(codemap, apiKey));
            httpClient.post();
            String content = httpClient.getContent();
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            //如果状态显示成功则修改数据库
            if (map.get("trade_state").equals("SUCCESS")){

                Date paytime = new Date();
                String tradestate=map.get("trade_state");
                oPayLogMapper.updatepaystatus(orderno,paytime,tradestate,orderno);
                OOrder order = new OOrder();
                order.setState(0);
                QueryWrapper<OOrder> wrapper = new QueryWrapper<>();
                wrapper.eq("code",orderno);
                wrapper.eq("state",1);
                oOrderMapper.update(order,wrapper);
                return new Result(2000,"支付成功");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(5000,"支付失败");
    }
}




